<template>
  <b-container fluid>

    <!-- 头图 -->
    <b-row>
      <NavigationBar :type="1" />
    </b-row>

    <!-- 第三行 是一个二级导航栏 -->
    <b-row>
      <b-container class="p-0">
        <!-- 分两列 右边则是信息栏-->
        <!-- sticky-top -->
        <b-row class="thirdRow mt-2">
          <!-- 左侧信息栏  -->
          <b-col class="col-3 mr-3">
            <b-row class="sticky-top border-sm rounded shadow-sm">
              <UpdateList />
            </b-row>
          </b-col>

          <!-- 社区卡片和导航栏 -->
          <!-- 下面变量其实写的有点傻逼,但不想改了,现在封装函数搞的很累 -->
          <b-col class="mr-3">
            <b-row class="sticky-top border shadow-sm rounded bg-light row-cols-4 text-center justify-content-center">
              <b-col class="col-auto mr-5 px-0 hvr-underline-reveal"
                :class="{ secondNavCol: this.$route.path == '/HomePage/HotListCard' }">
                <b-link class="px-5 text-decoration-none w-100 text-dark" to="/HomePage/HotListCard">推 荐</b-link>
              </b-col>
              <b-col class="col-auto ml-5 px-0 hvr-underline-reveal"
                :class="{ secondNavCol: this.$route.path == '/HomePage/SocialCard' }">
                <b-link class="px-5 text-decoration-none w-100 text-dark" to="/HomePage/SocialCard">社 区</b-link>
              </b-col>
            </b-row>
            <!-- 是选项卡片 需要路由了-->
            <b-row>
              <router-view v-if="cardShow" />
            </b-row>
          </b-col>

          <!-- 信息栏 嵌套只能在不同属性之间 col 套 row ; row 套 col 都可以 container 是用来限制宽度的一个容器-->
          <b-col class="col-3">
            <b-row class="sticky-top">
              <!-- 垂直设置信息栏 这是第一个的用户卡片 -->
              <b-col class="shadow-sm">
                <b-row class="border-bottom text-center">
                  <!-- 注意这里套了一下col 让col居中就不会影响到图标了 下面同 真傻比这操作 头像-->
                  <b-col class="pt-4"
                    style="background:url('https://t.lizi.moe/fj') center;background-size:100%;height:130px;border-top-right-radius: 4px;border-top-left-radius: 4px">
                    <b-avatar v-if="loginBtn" size="lg" />
                    <b-img v-else class="bg-white border" rounded="circle" height="75" width="75" :src="user.headUrl" />
                  </b-col>
                </b-row>
                <!-- 信息 -->
                <b-row class="avatarMessage border-bottom bg-light text-center">
                  <b-col class="border-right bg-light">
                    <b-row>
                      <b-col>等级</b-col>
                    </b-row>
                    <b-row>
                      <b-col>
                        <span>Lv</span>
                        <span v-if="user != null">{{ user.level }}</span>
                        <span v-else>--</span>
                      </b-col>
                    </b-row>
                  </b-col>
                  <b-col class="border-right bg-light">
                    <b-row>
                      <b-col>签到</b-col>
                    </b-row>
                    <b-row>
                      <b-col>
                        <span v-if="user != null">{{ user.days }}</span>
                        <span v-else>--</span>
                        <span>天</span>
                      </b-col>
                    </b-row>
                  </b-col>
                  <b-col class="bg-light">
                    <b-row>
                      <b-col>获赞</b-col>
                    </b-row>
                    <b-row>
                      <b-col>
                        <span v-if="user != null">{{ user.statistical.likeNum }}</span>
                        <span v-else>--</span>
                      </b-col>
                    </b-row>
                  </b-col>
                </b-row>
                <!-- 功能按钮 -->
                <b-row class="avatarButton text-center">
                  <b-col class="px-0">
                    <b-btn to="/login" v-if="loginBtn" class="w-100"
                      style="border-radius:0; border-bottom-left-radius: 4px;" variant="success">主页</b-btn>
                    <b-btn @click="userCard(1)" v-else class="w-100"
                      style="border-radius:0; border-bottom-left-radius: 4px;" variant="success">主页</b-btn>
                  </b-col>
                  <b-col v-show="check" class="px-0">
                    <b-btn to="/login" v-if="loginBtn" class="w-100" squared variant="warning">签到</b-btn>
                    <b-btn @click="userCard(2)" v-else class="w-100" squared variant="warning">签到</b-btn>
                  </b-col>
                  <b-col class="px-0">
                    <b-btn to="/login" v-if="loginBtn" class="w-100"
                      style="border-radius:0; border-bottom-right-radius: 4px;" variant="primary">登录</b-btn>
                    <b-btn @click="userCard(3)" v-else class="w-100"
                      style="border-radius:0; border-bottom-right-radius: 4px;" variant="danger">登出</b-btn>
                  </b-col>
                </b-row>
              </b-col>

              <!-- 垂直分布需要分割线 -->
              <div class="w-100" />

              <!-- 功能按键 -->
              <b-col class="mt-2">
                <b-row class="mt-2 justify-content-between">
                  <!-- 刷新按钮 -->
                  <b-col class="px-0 mr-2 text-center">
                    <b-list-group-item class="hvr-icon-spin" href="#" @click="refresh" v-b-tooltip.hover.bottom
                      title="刷新">
                      <span class="iconfont icon-refresh hvr-icon" style="font-size:16px" />
                    </b-list-group-item>
                  </b-col>
                  <b-col class="px-0 mr-2 text-center">
                    <!-- 发布动态 -->
                    <b-list-group-item class="hvr-float" href="#" @click="modelShow = true" v-b-tooltip.hover.bottom
                      title="发布动态">
                      <span class="iconfont icon-add" style="font-size:16px" />
                    </b-list-group-item>
                  </b-col>
                  <b-col class="px-0 mr-2 text-center">
                    <!-- 发布文章 -->
                    <b-list-group-item class="hvr-float" to="/IssueEditorPage" v-b-tooltip.hover.bottom title="发布文章">
                      <span class="iconfont icon-navigation" style="font-size:16px" />
                    </b-list-group-item>
                  </b-col>
                  <b-col v-if="topVisable" class="px-0 text-center">
                    <!-- 返回顶部 -->
                    <transition appear name="animate__animated animate__bounce" enter-active-class="animate__fadeInUp">
                      <b-list-group-item href="#" @click="toTop" v-b-tooltip.hover.bottom title="回到顶部">
                        <span class="iconfont icon-direction-up" style="font-size:16px" />
                      </b-list-group-item>
                    </transition>
                  </b-col>
                  <b-col v-else class="pl-0">
                    <!-- 返回顶部 替身 -->
                    <div style="height:1px;width:1px" />
                  </b-col>

                </b-row>
              </b-col>

            </b-row>
          </b-col>
        </b-row>

      </b-container>
    </b-row>

    <!-- 一个模拟框 -->
    <b-modal v-model="modelShow" title="想说点什么……" header-class="border-0" footer-class="border-0" button-size="sm"
      id="issue" hide-header-close ok-title="发布" cancel-title="取消" :no-close-on-backdrop="true" aria-hidden="true"
      centered @hidden="cancel" @ok="issue">
      <b-row v-show="upLoadPercentShow == false">
        <b-col>
          <b-textarea maxlength="200" autofocus v-model="dynamicIssue.textContent" class="textArea" no-resize />
        </b-col>
        <div class="w-100" />
        <b-col class="text-right" v-if="dynamicIssue.textContent.length != 0">
          <span v-show="dynamicIssue.textContent.length == 200" class="text-danger mr-2">输入达到上限</span>
          {{ dynamicIssue.textContent.length }}/200
        </b-col>
      </b-row>
      <b-row v-show="upLoadPercentShow == false" class="mt-2">
        <b-col class="pr-0 preview">
          <b-row v-for="img in dynamicIssue.imageUpload" :key="img.id">
            <!-- 预览图片 -->
            <b-col class="col-10">
              <viewer>
                <b-img thumbnail :name="img.id" :src="img.url" />
              </viewer>
            </b-col>
            <!-- 删除键 -->
            <b-col class="col-atuo p-0" align-self="center">
              <b-link class="text-danger" @click="deleteImg(img.id)">删除</b-link>
            </b-col>
          </b-row>
        </b-col>
        <b-col align-self="center" class="text-right pl-0 col-auto">
          <b-link @click="openFile" class="text-decoration-none" style="font-size:16px">
            <span class="iconfont icon-picture" /> 上传
          </b-link>
          <b-file accept=".jpg,.jpeg,.png,.gif" name="openFile" v-show="false" @change="readFile($event)" />
        </b-col>
      </b-row>
      <!-- 上传进度 -->
      <b-row v-show="upLoadPercentShow == true">
        <b-col>
          <b-progress>
            <b-progress-bar :value="percentCompleted" :label="`${percentCompleted}%`"></b-progress-bar>
          </b-progress>
        </b-col>
      </b-row>
    </b-modal>

  </b-container>
</template>

<script>
import toastr from 'toastr'
import { nanoid } from 'nanoid'
import NavigationBar from '../NavigationBar'
import UpdateList from './others/UpdateList'
export default {
  components: {
    // SocialCard
    NavigationBar,
    UpdateList,
  },
  name: "HomePage",
  data() {
    return {
      //控制刷新
      cardShow: true,
      //右下角返回顶部的显示与否
      topVisable: false,
      //动态发布对象实体 
      dynamicIssue: {
        //文本框内容监测
        textContent: "",
        //预览图片队列
        imageUpload: [],
        //控制图片上传按钮的显示
        upLoadShow: true,
      },
      //图片上传队列
      upLoadList: [],
      //每周番剧数据列表实体
      dailyList: {},
      //控制每周番剧的日期显示
      display: 0,
      //获取到的已经登录的用户
      user: null,
      //控制登录按钮的显示
      loginBtn: true,
      //控制签到按钮的显示
      check: true,
      //超时信息提示
      tip: false,
      //图片上传进度
      percentCompleted: null,
      //控制模拟框的开光
      modelShow: false,
      //控制上传进度的显示
      upLoadPercentShow: false,
    };
  },
  methods: {
    //监听滚动条
    scrolling() {
      let current =
        document.documentElement.scrollTop || document.body.scrollTop;
      if (current >= 700) {
        this.topVisable = true;
      } else {
        this.topVisable = false;
      }
    },

    //设置滚动条
    toTop() {
      let current =
        document.documentElement.scrollTop || document.body.scrollTop;
      const top = setInterval(() => {
        document.body.scrollTop = document.documentElement.scrollTop = current -= 50;
        if (current <= 0) {
          clearInterval(top);
        }
      }, 10);
    },

    //用户卡片操作函数 主页、签到、登出
    userCard(id) {
      switch (id) {
        case 1: this.$pageRedirect.toPersonPage(this.user.id); break;
        case 2: this.$httpUser.isUserCheck().then((res) => {
          if (res == true) return;
          this.$httpUser.checkIn(this.user.id).then((res) => {
            if (res == true) this.check = false;
            this.$httpUser.getUserInfo(this.user.id).then((res) => {
              this.user = res;
            })
          })
        }); break;
        case 3: this.$httpUser.loginOut(this.user.id); break;
      }
    },

    //刷新组件
    refresh() {
      this.cardShow = false;
      this.$nextTick(() => {
        this.cardShow = true;
      })
    },

    //上传图片
    openFile() {
      document.getElementsByName("openFile")[0].click();
    },

    //读取图片
    readFile(e) {
      //获取上传附件本地路径
      // const getFileURL = file => {
      //   var getUrl = null;
      //   if (window.createObjectURL != undefined) {
      //     // basic
      //     getUrl = window.createObjectURL(file);
      //   } else if (window.URL != undefined) {
      //     // mozilla(firefox)
      //     getUrl = window.URL.createObjectURL(file);
      //   } else if (window.webkitURL != undefined) {
      //     // webkit or chrome
      //     getUrl = window.webkitURL.createObjectURL(file);
      //   }
      //   return getUrl;
      // }

      if (this.dynamicIssue.imageUpload.length == 6) {
        toastr.error("图片已达上限");
        return
      }

      //获取input上传附件
      let file = e.target.files[0];
      this.upLoadList.push(file);

      // 上传附件路径
      // let src = getFileURL(file);
      // console.log("上传附件路径--->" + src);

      //获取base64数据
      let base64 = null;
      let reader = new FileReader();
      let _this = this;
      reader.readAsDataURL(file);
      reader.onload = function (e) {
        base64 = e.target.result;

        var obj = {};
        obj.id = nanoid(4);
        obj.url = base64;

        _this.dynamicIssue.imageUpload.push(obj)
      }

    },

    //取消模拟框
    cancel() {
      if (this.dynamicIssue.textContent != null) {
        localStorage.setItem("dynamicEditor", this.dynamicIssue.textContent);
      }
      this.dynamicIssue.imageUpload = null;
    },

    //确认发送动态
    issue(event) {
      event.preventDefault()
      this.upLoadPercentShow = true;
      if (this.user == null) {
        toastr.error("先登录!");
        return
      }
      let temp = this.dynamicIssue.textContent.replace(/\s+/g, '');
      if (temp == null || temp.length == 0) {
        toastr.error("文本框不能纯为空!");
        return
      }
      //封装动态对象
      var dynamic = JSON.stringify({
        userId: this.user.id,
        content: this.dynamicIssue.textContent,
      });
      //转换为json请求头
      dynamic = new Blob([dynamic], {
        type: 'application/json',
      })
      //创建表单对象
      let formData = new FormData();
      let path = "/issue_text";
      if (this.upLoadList.length != 0) {
        this.upLoadList.forEach((file) => {
          formData.append("file", file);
        });
        path = "/issue_file"

      }
      formData.append("dynamic", dynamic);
      //文件上传进度检测变量
      const handleUploadProgress = (progress) => {
        // 处理进度数据
        this.percentCompleted = Math.round(progress.loaded * 100 / progress.total)
        if (Math.round(progress.loaded * 100 / progress.total) == 100) {
          this.modelShow = false;
          this.upLoadPercentShow = false;
        }
        // console.log('Upload Progress:', Math.round(progress.loaded * 100 / progress.total))
      }
      //请求插入数据
      this.$httpIssue.dynamicIssue(formData, path, handleUploadProgress).then((res) => {
        if (res == true) {
          setTimeout(() => {
            this.$router.replace({
              path: "/HomePage/SocialCard"
            });
          }, 2000)
          localStorage.removeItem("dynamicEditor");
        }
      });
      this.dynamicIssue.imageUpload = null;
    },

    //删除图片
    deleteImg(id) {
      var newImageArr = [];
      var newFileArr = [];
      for (let i = 0; i < this.dynamicIssue.imageUpload.length; i++) {
        if (this.dynamicIssue.imageUpload[i].id == id) {
          continue;
        }
        newImageArr.push(this.dynamicIssue.imageUpload[i]);
        newFileArr.push(this.upLoadList[i])
      }
      this.dynamicIssue.imageUpload = newImageArr;
      this.upLoadList = newFileArr;
      // for (let j = 0; j < this.dynamicIssue.imageUpload.length; j++) {
      //   console.log(this.dynamicIssue.imageUpload[j].id);
      // }
    },
  },
  mounted() {
    // 添加监听事件
    window.addEventListener("scroll", this.scrolling);
    //读取动态编辑草稿
    if (localStorage.getItem("dynamicEditor") != null) {
      this.dynamicIssue.textContent = localStorage.getItem("dynamicEditor");
    }
  },
  created() {

    let hour = new Date().getHours();
    if (hour < 12) document.title = "WaaFun首页~(๑> <)☆上午好呀!元气一天!";
    if (hour >= 12 && hour <= 13) document.title = "WaaFun首页~(๑> <)☆中午好呀!吃饭了吗!";
    if (hour > 13 && hour <= 18) document.title = "WaaFun首页~(๑> <)☆下午好呀!好困啊!";
    if (hour > 18) document.title = "WaaFun首页~(๑> <)☆晚上好呀!干点什么呢";


    //获取每周番剧更新的数据
    this.$httpBangumi.getDailyBangumi().then((res) => {
      if (res == "timeOut") {
        this.tip = true;
        this.loading = false;
        return
      }
      if (res.data != null) {
        this.dailyList = res.data;
        this.display = res.display;
        this.loading = false;
      }
    });

    //检查用户是否登录
    this.$httpUser.isUserLogin().then(async (res) => {
      if (res != null) {
        await this.$httpUser.getUserInfo(res, 1).then((res) => {
          this.user = res;
        });
        toastr.success("欢迎你!  " + this.user.name, '登录成功!', { timeOut: 3000 });
        this.loginBtn = false;
        //检查用户是否签到
        await this.$httpUser.isUserCheck(this.user.id).then((res) => {
          if (res == true) {
            this.check = false;
          }
        })
      }
    });


  },
  destroyed() {
    // 销毁监听事件
    window.removeEventListener("scroll", this.scrolling);
  }
}
</script>

<style scoped>
.avatarMessage,
.avatarButton,
.fanjuList,
.repal {
  font-family: HYZhengYuan-55S;
}

.col {
  margin-right: 0;
}

.thirdRow {
  font-size: 20px;
}

.secondNav {
  border-top: solid 1px #afddf8;
}

.secondNav div a {
  font-family: HYZhengYuan-55S;
  color: black;
}

.secondNav div {
  padding-top: 0.5%;
  padding-bottom: 0.5%;
}

.secondNavCol {
  border-bottom: solid 2px #0c91de;
}

.avatarRow {
  border-top: solid 1px #afddf8;
}

.avatarMessage {
  font-size: 16px;
}

.avatarMessage div div div {
  padding-top: 6%;
  padding-bottom: 6%;
}

.textArea {
  height: 180px;
  font-size: 15px;
}

.textArea:focus,
.btn:focus {
  outline: none;
  box-shadow: none;
}

.clickWeekBtn {
  background: aliceblue;
}

.fanjuListBox {
  height: 320px;
  overflow: hidden;
}

.fanjuListBox:hover {
  overflow-y: overlay;
}

::-webkit-scrollbar {
  width: 4px;
}

::-webkit-scrollbar-thumb {
  border-radius: 10px;
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  background: rgba(0, 0, 0, 0.2);
}

::-webkit-scrollbar-track {
  box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
  border-radius: 0;
  background: rgba(0, 0, 0, 0.1);
}

.fanju:hover {
  cursor: pointer;
}

.preview {
  max-height: 300px;
  overflow: hidden;
}

.preview:hover {
  max-height: 300px;
  overflow-y: overlay;
  overflow-x: hidden;
}
</style>
